<template>
  <div class="index">
    <div id='main'>
      <UploadBigFile></UploadBigFile>

      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item class="breadcrumb-clickable" v-for="(item, idex) in curCataloguePathList"
          @click="handlerSelectCatalogue(item)">{{ item.name }}</el-breadcrumb-item>
      </el-breadcrumb>

      <div class='all-file'>
        <span class="title">全部文件</span>

        <!-- 批量删除 -->
        <div class="toolbar">
          <el-button type="primary" @click="openaddDialog">
            创建目录
          </el-button>
          <el-button :disabled="selectedRows.length === 0" type="primary" @click="handlerSelect">
            修改名称
          </el-button>
          <el-button :disabled="selectedRows.length === 0" type="danger" @click="batchDelete">
            批量删除
          </el-button>
        </div>

        <!-- 目录表格 -->
        <el-table ref="tableRef" :data="curCatalogue" style="width: 100%; margin-top: 8px" @row-click="handleRowClick"
          @selection-change="handleSelectionChange" empty-text="空空如也">
          <!-- 复选框列 -->
          <el-table-column type="selection" width="40" align="center" />

          <!-- 目录名（可编辑） -->
          <el-table-column label="名称">
            <template #default="{ row, $index }">
              <!-- 编辑态 -->
              <el-input v-if="row.editing" v-model="row.name" size="small" @blur="finishEdit(row)"
                @keyup.enter="finishEdit(row)" @click.stop />
              <!-- 展示态 -->
              <span v-else @dblclick.stop="startEdit(row)" class="dir-name">
                {{ row.name }}
              </span>


              <!-- 2️⃣ 展示态（新增图标按钮） -->
              <span v-else @dblclick.stop="startEdit(row)" class="dir-name name-box">
                {{ row.name }}

                <!-- 3️⃣ 悬浮图标按钮（新增） -->
                <span class="row-actions">
                  <!-- 修改图标 -->
                  <el-icon title="修改名称" class="action-icon" @click.stop="startEdit(row)">
                    <Edit />
                  </el-icon>

                  <!-- 删除图标 -->
                  <el-icon title="删除" class="action-icon" @click.stop="removeRow(row)">
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </template>
          </el-table-column>

          <!-- 其他列（可按需扩展） -->
          <el-table-column prop="createdTime" label="创建日期" width="320" />
          <el-table-column prop="size" label="大小" width="100" />
        </el-table>
      </div>

    </div>

    <el-dialog v-model="addDialogVisible" title="创建新目录" width="500">
      <el-form>
        <el-form-item label="目录名称">
          <el-input v-model="addCatalogueName" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handlerddCatalogue">创建</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import UploadBigFile from '@/components/UploadBigFile.vue';

import { ref, onMounted, onUnmounted } from 'vue';
import { ArrowRight, Edit, Delete } from '@element-plus/icons-vue'

import { ElTable, ElTableColumn, ElButton, ElInput, ElNotification, ElMessageBox } from 'element-plus'

import { catalogueList, updateCatalogueName, catalogueDelete, catalogueBatchDelete, catalogueAdd } from '@/network/user/api_catalogue'
import { CATALOGUE_DEFAULT_INDEX } from "@/common_js/userInteface_common"

import eventBus from '@/stores/eventBus' // 全局事件，属性目录使用

// 实时更新 curCatalogueParentId
import { useDirStore } from '@/stores/dirStore'
const dirStore = useDirStore()

onMounted(() => {
  // console.log('组件挂载完成后调用');
  getCatalogueList();
  eventBus.on('update-catalogue-list', handlerUpdateCatalogueList);
});

onUnmounted(() => {
  eventBus.off('update-catalogue-list', handlerUpdateCatalogueList); // 清理监听器
});

interface DirItem {
  id: string
  catalogueId: string
  name: string
  userId: string
  createdTime: string
  parentId: string
  size?: string
  editing?: boolean
  children?: [string, DirItem][]  // 做缓存使用，暂时不做
}

interface RawItem {
  id: number
  catalogueId: string
  type: boolean
  userId: string
  name: string
  parentId: string
  createdTime: string
  size?: string
  children: RawItem[] | null
}

function transform(raw: RawItem): DirItem {
  const item: DirItem = {
    id: String(raw.id),
    catalogueId: raw.catalogueId,
    name: raw.name,
    userId: raw.userId,
    parentId: raw.parentId,
    createdTime: raw.createdTime,
    size: raw.size ?? '-',        // ← 如果后端没给 size，就用 '-'
    // editing: false,               // 如有需要也可以给 editing 默认值
    children: raw.children
      ? raw.children.map(child => [
        child.catalogueId,
        transform(child)
      ] as [string, DirItem])
      : []
  }
  return item
}

const tableData = ref<DirItem[]>([
  // { id: '1', name: '文档', date: '2024-06-11 10:20', size: '—' },
  // { id: '2', name: '下载', date: '2024-06-10 14:32', size: '—' },
  // { id: '3', name: '项目', date: '2024-06-09 09:55', size: '—' }
])

const tableRef = ref<InstanceType<typeof ElTable>>()
const selectedRows = ref<DirItem[]>([])

/* ===== 复选框变化 ===== */
function handleSelectionChange(rows: DirItem[]) {
  selectedRows.value = rows
}

/* ===== 单击整行 ===== */
function handleRowClick(row: DirItem) {
  // 让当前行高亮
  tableRef.value!.setCurrentRow(row)
  curCatalogueParentId.value = row.catalogueId
  dirStore.setCurrentDir(curCatalogueParentId)   // 更新全局
  getCatalogueList().then(dirItems => {
    // 更新面包屑路径
    curCataloguePathList.value.push(new Catalogue(row.catalogueId, row.name));
  })
}

/* ===== 双击进入编辑 ===== */
function startEdit(row: DirItem) {
  // 先关闭其他行的编辑
  tableData.value.forEach(r => (r.editing = false))
  row.editing = true
}

/* ===== 完成编辑 ===== */
function finishEdit(row: DirItem) {
  row.editing = false
  // 可在此发送 API 保存新名称
  updateCatalogueName(row).then(resp => {
    ElNotification({
      title: 'Success',
      message: '修改名称成功',
      type: 'success',
    })
  }).catch(error => {
    console.log(error);
  });
}

/* ===== 单行删除 ===== */
function removeRow(row: DirItem) {
  ElMessageBox.confirm(`确定删除 “${row.name}” 吗？`, '提示')
    .then(() => {
      catalogueDelete(row.id).then(res => {
        // ElNotification({
        //   title: 'Success',
        //   message: '删除成功',
        //   type: 'success',
        // })
        curCatalogue.value = curCatalogue.value.filter(r => r.id !== row.id)
      })
    })
    .catch(() => { })
}

/* ===== 批量删除 ===== */
function batchDelete() {
  ElMessageBox.confirm(`确定全部删除吗？`, '提示')
    .then(() => {
      const ids = selectedRows.value.map(r => r.id)
      catalogueBatchDelete(ids).then(res => {
        ids.forEach(id => {
          curCatalogue.value = curCatalogue.value.filter(r => r.id !== id)
        })
      })
      selectedRows.value = []
    })
    .catch(() => { })
}

/* ===== 选择修改名称，只能单个 ===== */
function handlerSelect() {
  const ids = selectedRows.value.map(r => r.id)
  if (ids.length > 1) {
    ElNotification({
      title: 'Warning',
      message: '不允许批量修改',
      type: 'warning',
    })
    return;
  }
  // 1. 拿到位于 tableData 里的对象
  const target = selectedRows.value[0];
  if (!target) return
  // 2. 先关闭所有编辑
  tableData.value.forEach(r => (r.editing = false))
  // 3. 再设置当前编辑
  target.editing = true
  // 清空选中（也可保留，看交互需要）
  // selectedRows.value = []
}




class Catalogue {
  id: string;
  name: string;
  constructor(id: string, name: string) {
    this.id = id;
    this.name = name;
  }
}

// const curCatalogue = ref<Catalogue[]>();
const curCataloguePathList = ref<Catalogue[]>([
  new Catalogue('/index', "首页"),
]);


/** 面包屑路径选择 **/
const handlerSelectCatalogue = (item: Catalogue) => {
  curCatalogueParentId.value = item.id
  dirStore.setCurrentDir(curCatalogueParentId)   // 更新全局
  getCatalogueList().then(dirItems => {
    const idx = curCataloguePathList.value.findIndex(n => n.id === item.id);
    if (idx === -1) return;                   // 未找到，直接退出
    // 下标 +1 即为要保留的节点数量，其余从尾部全部干掉
    curCataloguePathList.value.splice(idx + 1);
  })
}

const curCatalogueParentId = ref(CATALOGUE_DEFAULT_INDEX);
const curCatalogue = ref<DirItem[]>([]);


const getCatalogueList = () => {
  return catalogueList({ catalogueId: curCatalogueParentId.value })
    .then((res) => {
      // console.log(res.data);
      const rawData: RawItem[] = res.data // 原始数据
      const dirItems: DirItem[] = rawData.map(transform)
      curCatalogue.value = dirItems
      return dirItems          // 关键：把结果继续向下传递
    })
    .catch(error => {
      console.error(error)
      throw error             // 继续往外抛，给调用方 catch
    })
}

const addDialogVisible = ref(false);
const addCatalogueName = ref('')
const openaddDialog = () => {
  addCatalogueName.value = '';  // 清空名称
  addDialogVisible.value = true;
}

/** 确定添加目录 **/
const handlerddCatalogue = () => {
  const from = {
    "id": undefined,
    "catalogueId": undefined,
    "type": 0,
    "userId": undefined,
    "name": addCatalogueName.value,
    "parentId": curCatalogueParentId.value
  }
  catalogueAdd(from).then(res => {
    ElNotification({
      title: 'Success',
      message: '创建新目录成功',
      type: 'success',
    })
    getCatalogueList()    // 添加成功再更新目录
  })
  addDialogVisible.value = false
}

const handlerUpdateCatalogueList = () => {
  getCatalogueList()
}

</script>

<style scoped>
#main {
  width: 90vw;
  border: 1px solid black;
}

.el-breadcrumb {
  margin: 10px;
  font-size: 20px;
}

::v-deep(.el-breadcrumb .el-breadcrumb__inner) {
  color: black !important;
}

.breadcrumb-clickable {
  cursor: pointer;
}

.title {
  display: block;
  /* 让 span 占整行，text-align 才生效 */
  text-align: left;
  font-size: 16px;
  font-weight: bold;
  margin: 10px;
}

.toolbar {
  display: flex;
  justify-content: flex-start;
  /* 关键：靠左 */
  margin-bottom: 8px;
}

/* 名称列容器 */
.name-box {
  display: inline-flex;
  align-items: center;
  width: 100%;
}

/* 图标容器：默认隐藏 */
.row-actions {
  margin-left: auto;
  display: inline-flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

/* 鼠标悬停行时显示图标 */
.el-table__row:hover .row-actions {
  opacity: 1;
}

/* 图标样式 */
.action-icon {
  cursor: pointer;
  color: #606266;
}

.action-icon:hover {
  color: var(--el-color-primary);
}

.dir-name {
  cursor: pointer;
  user-select: none;
}

.dir-name:hover {
  color: var(--el-color-primary);
}
</style>
